/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.thinkinbunny.httpUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.thinkinbunny.json.JSONArray;
import org.thinkinbunny.json.JSONObject;
import org.thinkinbunny.control.ApiUpdateFromClient;
import org.thinkinbunny.data.BillEntiry;
import org.thinkinbunny.data.DbHelper;
import org.thinkinbunny.data.User;


/**
 *
 * @author yfxiawei
 */
public class ProcessRequest {

    public static void processRequestMain(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/json;charset=UTF-8");
        String functionId = request.getParameter("functionId");
        String result = "";
        DbHelper dbHelper = new DbHelper();
        dbHelper.OpenDb();
        try {


            /*
             * 读取数据
             */
            BufferedReader br = new BufferedReader(
                    new InputStreamReader((ServletInputStream) request.getInputStream(), "utf-8"));
            StringBuffer sb = new StringBuffer("");
            String temp;
            while ((temp = br.readLine()) != null) {
                sb.append(temp);
            }
            br.close();
            result = sb.toString();
            System.out.println("请求报文:" + result);


            JSONObject jsono = new JSONObject(result);
            Log.i("processRequestMain", jsono.toString());
            JSONArray jarray = new JSONArray(jsono.getString("message"));
            User user = new User(jsono.getString("username"), jsono.getString("password"));
            if (!dbHelper.CheckUser(user)) {
                processRequestError(request, response);
                return;
            }
            JSONObject billJSONObject = new JSONObject();
            BillEntiry billEntiry = new BillEntiry();

            dbHelper.updateMainClear(user);
            for (int i = 0; i < jarray.length(); i++) {
                billJSONObject = jarray.getJSONObject(i);
                billEntiry.setProject(billJSONObject.getString("project"));
                billEntiry.setBillType(billJSONObject.getString("billType"));
                billEntiry.setBalance(Float.parseFloat((billJSONObject.getString("balance"))));
                billEntiry.setTime(billJSONObject.getString("time"));
                billEntiry.setAccountname(billJSONObject.getString("accountname"));
                billEntiry.setDate(billJSONObject.getString("date"));
                billEntiry.setStore(billJSONObject.getString("store"));
                dbHelper.updateMain(billEntiry,user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            dbHelper.CLoseDb();
            try {
                /*
                 * 返回数据
                 */


                PrintWriter pw = response.getWriter();
                pw.write(result);
                pw.flush();


                System.out.println("返回报文:" + result + functionId);

            } catch (Exception ex) {
                Logger.getLogger(ApiUpdateFromClient.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    public static void processRequestAccount(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/json;charset=UTF-8");
        DbHelper dbHelper = new DbHelper();
        String result = "";

        JSONObject retJSONObject = new JSONObject();

        try {
            dbHelper.OpenDb();
            BufferedReader br = new BufferedReader(
                    new InputStreamReader((ServletInputStream) request.getInputStream(), "utf-8"));
            StringBuffer sb = new StringBuffer("");
            String temp;
            while ((temp = br.readLine()) != null) {
                sb.append(temp);
            }
            br.close();
            result = sb.toString();
            System.out.println("请求报文:" + result);
            JSONObject jsono = new JSONObject(result);
             Log.i("processRequestAccount", jsono.toString());
            JSONArray jarray = new JSONArray(jsono.getString("message"));
            User user = new User(jsono.getString("username"), jsono.getString("password"));
            if (!dbHelper.CheckUser(user)) {
                processRequestError(request, response);
                return;
            }
            JSONObject billJSONObject = new JSONObject();
            //       BillEntiry billEntiry = new BillEntiry();


            for (int i = 0; i < jarray.length(); i++) {
                billJSONObject = jarray.getJSONObject(i);

                dbHelper.updateAccount(billJSONObject.getString("account"),user);
            }

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            dbHelper.CLoseDb();
            try {


                PrintWriter pw = response.getWriter();
                pw.write(result);
                pw.flush();

                //      pw.write(jarray.toString());


                System.out.println("返回报文:" + result);
            } catch (Exception ex) {
                Logger.getLogger(ApiUpdateFromClient.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    public static void processRequestProject(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/json;charset=UTF-8");

        String result = "";
        Statement sm = null;
        ResultSet rs = null;
        Connection ct = null;
        DbHelper dbHelper = new DbHelper();
        try {
            dbHelper.OpenDb();

            /*
             * 读取数据
             */
            BufferedReader br = new BufferedReader(
                    new InputStreamReader((ServletInputStream) request.getInputStream(), "utf-8"));
            StringBuffer sb = new StringBuffer("");
            String temp;
            while ((temp = br.readLine()) != null) {
                sb.append(temp);
            }
            br.close();
            result = sb.toString();
            System.out.println("请求报文:" + result);


            JSONObject jsono = new JSONObject(result);
             Log.i("processRequestProject", jsono.toString());
            JSONArray jarray = new JSONArray(jsono.getString("message"));
            User user = new User(jsono.getString("username"), jsono.getString("password"));
            if (!dbHelper.CheckUser(user)) {
                processRequestError(request, response);
                return;
            }
            JSONObject billJSONObject = new JSONObject();
            for (int i = 0; i < jarray.length(); i++) {
                billJSONObject = jarray.getJSONObject(i);
                dbHelper.updateProject(billJSONObject.getString("project"),user);
            }
        } catch (Exception e) {
        } finally {
            dbHelper.CLoseDb();
            try {
                /*
                 * 返回数据
                 */


                PrintWriter pw = response.getWriter();
                pw.write(result);
                pw.flush();

                //      pw.write(jarray.toString());

                pw.flush();

                pw.close();
                System.out.println("返回报文:" + result);
            } catch (Exception ex) {
                Logger.getLogger(ApiUpdateFromClient.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    public static void processRequestType(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/json;charset=UTF-8");

        String result = "";
        Statement sm = null;
        ResultSet rs = null;
        Connection ct = null;
        DbHelper dbHelper = new DbHelper();
        try {
            dbHelper.OpenDb();
            BufferedReader br = new BufferedReader(
                    new InputStreamReader((ServletInputStream) request.getInputStream(), "utf-8"));
            StringBuffer sb = new StringBuffer("");
            String temp;
            while ((temp = br.readLine()) != null) {
                sb.append(temp);
            }
            br.close();
            result = sb.toString();
            System.out.println("请求报文:" + result);


            JSONObject jsono = new JSONObject(result);
                 Log.i("processRequestType", jsono.toString());
            JSONArray jarray = new JSONArray(jsono.getString("message"));
            User user = new User(jsono.getString("username"), jsono.getString("password"));
            if (!dbHelper.CheckUser(user)) {
                processRequestError(request, response);
                return;
            }
            JSONObject billJSONObject = new JSONObject();



            for (int i = 0; i < jarray.length(); i++) {
                billJSONObject = jarray.getJSONObject(i);

                dbHelper.updateType(billJSONObject.getString("type"),user);
            }
        } catch (Exception e) {
        } finally {
            dbHelper.CLoseDb();
            try {
                /*
                 * 返回数据
                 */


                PrintWriter pw = response.getWriter();
                pw.write(result);
                pw.flush();

                //      pw.write(jarray.toString());


                System.out.println("返回报文:" + result);
            } catch (Exception ex) {
                Logger.getLogger(ApiUpdateFromClient.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    public static void processRequestMainToClient(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/json;charset=UTF-8");

        String result = "";
        DbHelper dbHelper = new DbHelper();
        Statement sm = null;
        ResultSet rs = null;
        Connection ct = null;
        try {
            dbHelper.OpenDb();
             User user;
            {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader((ServletInputStream) request.getInputStream(), "utf-8"));
                StringBuffer sb = new StringBuffer("");
                String temp;
                while ((temp = br.readLine()) != null) {
                    sb.append(temp);
                }
                br.close();
                result = sb.toString();

                JSONObject userJSONObject = new JSONObject(result);
                System.out.println("请求报文:" + result + "||" + userJSONObject.toString());
                 user = new User(userJSONObject.getString("username").toString(), userJSONObject.getString("password").toString());
                if (!dbHelper.CheckUser(user)) {
                    processRequestError(request, response);
                    return;
                }
            }

            result = dbHelper.UpdateMainTOClient(user).toString();
            JSONObject jsono = new JSONObject();
            jsono.put("message", dbHelper.UpdateMainTOClient(user));

            PrintWriter pw = response.getWriter();
            pw.write(jsono.toString());
            pw.flush();
            System.out.println("返回报文:" + result);
        } catch (Exception ex) {
            Logger.getLogger(ApiUpdateFromClient.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            dbHelper.CLoseDb();
        }
    }

    public static void processRequestAccountToClient(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/json;charset=UTF-8");

        String result = "";
        DbHelper dbHelper = new DbHelper();
        Statement sm = null;
        ResultSet rs = null;
        Connection ct = null;
        try {
            dbHelper.OpenDb();
               User user ;
            {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader((ServletInputStream) request.getInputStream(), "utf-8"));
                StringBuffer sb = new StringBuffer("");
                String temp;
                while ((temp = br.readLine()) != null) {
                    sb.append(temp);
                }
                br.close();
                result = sb.toString();
                System.out.println("请求报文:" + result);
                JSONObject userJSONObject = new JSONObject(result);

             user= new User(userJSONObject.getString("username"), userJSONObject.getString("password"));
                if (!dbHelper.CheckUser(user)) {
                    processRequestError(request, response);
                    return;
                }
            }

            result = dbHelper.UpdateAccountTOClient(user).toString();
            JSONObject jsono = new JSONObject();
            jsono.put("message", dbHelper.UpdateAccountTOClient(user));
              //     User user=new User(jsono.getString("username"), jsono.getString("password"));
//            if (!dbHelper.CheckUser(user)) {
//                processRequestError(request, response);
//                return;
//            }
            PrintWriter pw = response.getWriter();
            pw.write(jsono.toString());
            pw.flush();
            System.out.println("返回报文:" + result);
        } catch (Exception ex) {
            Logger.getLogger(ApiUpdateFromClient.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            dbHelper.CLoseDb();
        }
    }

    public static void processRequestProjectoClient(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/json;charset=UTF-8");

        String result = "";
        DbHelper dbHelper = new DbHelper();
        Statement sm = null;
        ResultSet rs = null;
        Connection ct = null;
        try {
            dbHelper.OpenDb();
            User user;
            {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader((ServletInputStream) request.getInputStream(), "utf-8"));
                StringBuffer sb = new StringBuffer("");
                String temp;
                while ((temp = br.readLine()) != null) {
                    sb.append(temp);
                }
                br.close();
                result = sb.toString();
                System.out.println("请求报文:" + result);
                JSONObject userJSONObject = new JSONObject(result);

                 user = new User(userJSONObject.getString("username"), userJSONObject.getString("password"));
                if (!dbHelper.CheckUser(user)) {
                    processRequestError(request, response);
                    return;
                }
            }


            result = dbHelper.UpdateProjectTOClient(user).toString();
            JSONObject jsono = new JSONObject();
            jsono.put("message", dbHelper.UpdateProjectTOClient(user));
 
            PrintWriter pw = response.getWriter();
            pw.write(jsono.toString());
            pw.flush();
            System.out.println("返回报文:" + result);
        } catch (Exception ex) {
            Logger.getLogger(ApiUpdateFromClient.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            dbHelper.CLoseDb();
        }
    }

    public static void processRequestTypeToClient(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/json;charset=UTF-8");

        String result = "";
        DbHelper dbHelper = new DbHelper();
        Statement sm = null;
        ResultSet rs = null;
        Connection ct = null;
        try {
             User user;
            dbHelper.OpenDb();
            {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader((ServletInputStream) request.getInputStream(), "utf-8"));
                StringBuffer sb = new StringBuffer("");
                String temp;
                while ((temp = br.readLine()) != null) {
                    sb.append(temp);
                }
                br.close();
                result = sb.toString();
                System.out.println("请求报文:" + result);
                JSONObject userJSONObject = new JSONObject(result);

                user= new User(userJSONObject.getString("username"), userJSONObject.getString("password"));
                if (!dbHelper.CheckUser(user)) {
                    processRequestError(request, response);
                    return;
                }
            }

            result = dbHelper.UpdateTypeTOClient(user).toString();
            JSONObject jsono = new JSONObject();
            jsono.put("message", dbHelper.UpdateTypeTOClient(user));
            PrintWriter pw = response.getWriter();
            pw.write(jsono.toString());
            pw.flush();
            System.out.println("返回报文:" + result);
        } catch (Exception ex) {
            Logger.getLogger(ApiUpdateFromClient.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            dbHelper.CLoseDb();
        }
    }

    public static void processRequestError(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/json;charset=UTF-8");

        String result = "error";
        JSONArray jarray = null;
        try {

            /*
             * 读取数据
             */
//            BufferedReader br = new BufferedReader(
//                    new InputStreamReader((ServletInputStream) request.getInputStream(), "utf-8"));
//            StringBuffer sb = new StringBuffer("");
//            String temp;
//            while ((temp = br.readLine()) != null) {
//                sb.append(temp);
//            }
//            br.close();
//            result = sb.toString();
            //  JSONObject jsono = new JSONObject(result);
            jarray = new JSONArray();
            JSONObject billJSONObject = new JSONObject();
            billJSONObject.put("code", "error");
            jarray.put(billJSONObject);
            result = jarray.toString();
            System.out.println("请求报文:" + result);




            //   BillEntiry billEntiry=new BillEntiry();
//            DbHelper dbHelper=new DbHelper();

//            for (int i = 0; i < jarray.length(); i++) {
//                billJSONObject=jarray.getJSONObject(i);
//                billEntiry.setProject(billJSONObject.getString("project"));
//                billEntiry.setBillType(billJSONObject.getString("billType"));
//                billEntiry.setTime(billJSONObject.getString("time"));
//                billEntiry.setAccountname(billJSONObject.getString("accountname"));
//                billEntiry.setDate(billJSONObject.getString("date"));
//                billEntiry.setStore(billJSONObject.getString("store"));
//               dbHelper.updateMain(billEntiry);
//            }
        } catch (Exception e) {
        } finally {
            try {
                PrintWriter pw = response.getWriter();
                pw.write(result);
                pw.flush();
                pw.close();
                System.out.println("返回报文:" + result);
            } catch (Exception ex) {
                Logger.getLogger(ApiUpdateFromClient.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    public static void processRequestCheckVersion(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/json;charset=UTF-8");

        String result = "";
        DbHelper dbHelper = new DbHelper();
        Statement sm = null;
        ResultSet rs = null;
        Connection ct = null;
        try {

            dbHelper.OpenDb();
            result = dbHelper.UpdateVersion(request.getParameter("ver")).toString();
            JSONObject jsono = new JSONObject();
            jsono.put("message", dbHelper.UpdateVersion(request.getParameter("ver")));
            PrintWriter pw = response.getWriter();
            pw.write(jsono.toString());
            pw.flush();
            System.out.println("返回报文:" + result + request.getParameter("uuid"));
        } catch (Exception ex) {
            Logger.getLogger(ApiUpdateFromClient.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            dbHelper.CLoseDb();
        }
    }

    public static void processRequestCheckUser(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/json;charset=UTF-8");

        String result = "";
        DbHelper dbHelper = new DbHelper();
        Statement sm = null;
        ResultSet rs = null;
        Connection ct = null;
        try {

            dbHelper.OpenDb();
            result = dbHelper.UpdateVersion(request.getParameter("ver")).toString();
            JSONObject jsono = new JSONObject();
            //jsono.put("message", dbHelper.updateProject(request.getParameter("ver")));
            PrintWriter pw = response.getWriter();
            pw.write(jsono.toString());
            pw.flush();
            System.out.println("返回报文:" + result + request.getParameter("uuid"));
        } catch (Exception ex) {
            Logger.getLogger(ApiUpdateFromClient.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            dbHelper.CLoseDb();
        }
    }
     public static void processRequestLogin(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/json;charset=UTF-8");

        String result = "";
        Statement sm = null;
        ResultSet rs = null;
        Connection ct = null;
        DbHelper dbHelper = new DbHelper();
         JSONObject userjson = new JSONObject();
        try {
            dbHelper.OpenDb();
            BufferedReader br = new BufferedReader(
                    new InputStreamReader((ServletInputStream) request.getInputStream(), "utf-8"));
            StringBuffer sb = new StringBuffer("");
            String temp;
            while ((temp = br.readLine()) != null) {
                sb.append(temp);
            }
            br.close();
            result = sb.toString();
            System.out.println("请求报文:" + result);


            JSONObject jsono = new JSONObject(result);
             Log.i("processRequestLogin", jsono.toString());
          //  JSONArray jarray = new JSONArray(jsono.getString("message"));
            User user = new User(jsono.getString("username"), jsono.getString("password"));
            if (!dbHelper.CheckUser(user)) {
                processRequestError(request, response);
                return;
            }
            
           
            userjson.put("message", jsono);



//            for (int i = 0; i < jarray.length(); i++) {
//                billJSONObject = jarray.getJSONObject(i);
//
//                dbHelper.updateType(billJSONObject.getString("type"),user);
//            }
        } catch (Exception e) {
            e.printStackTrace();
              processRequestError(request, response);
        } finally {
            dbHelper.CLoseDb();
            try {
                /*
                 * 返回数据
                 */


                PrintWriter pw = response.getWriter();
                pw.write( userjson.toString());
                pw.flush();

                //      pw.write(jarray.toString());


                System.out.println("返回报文:" + userjson.toString());
            } catch (Exception ex) {
                Logger.getLogger(ApiUpdateFromClient.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }
       public static void processRequestRegister(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/json;charset=UTF-8");

        String result = "";
        Statement sm = null;
        ResultSet rs = null;
        Connection ct = null;
        DbHelper dbHelper = new DbHelper();
         JSONObject userjson = new JSONObject();
        try {
            dbHelper.OpenDb();
            BufferedReader br = new BufferedReader(
                    new InputStreamReader((ServletInputStream) request.getInputStream(), "utf-8"));
            StringBuffer sb = new StringBuffer("");
            String temp;
            while ((temp = br.readLine()) != null) {
                sb.append(temp);
            }
            br.close();
            result = sb.toString();
            System.out.println("请求报文:" + result);


            JSONObject jsono = new JSONObject(result);
          //  JSONArray jarray = new JSONArray(jsono.getString("message"));
            User user = new User(jsono.getString("username"), jsono.getString("password"));
            user.setEmail(jsono.getString("email"));
            if (!dbHelper.registerUser(user)) {
                processRequestError(request, response);
                return;
            }
            
           
            userjson.put("message", jsono);



//            for (int i = 0; i < jarray.length(); i++) {
//                billJSONObject = jarray.getJSONObject(i);
//
//                dbHelper.updateType(billJSONObject.getString("type"),user);
//            }
        } catch (Exception e) {
            e.printStackTrace();
              processRequestError(request, response);
        } finally {
            dbHelper.CLoseDb();
            try {


                PrintWriter pw = response.getWriter();
                pw.write( userjson.toString());
                pw.flush();

                System.out.println("返回报文:" + userjson.toString());
            } catch (Exception ex) {
                Logger.getLogger(ApiUpdateFromClient.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

}
